<!DOCTYPE html>
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
    <meta charset="UTF-8">
    <title>用户个人资料</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            height: 100vh;
            background-color: #f4f4f4;
            color: #333;
        }

        h2, h3 {
            color: #70eaf3;
        }

        a {
            color: #70eaf3;
            text-decoration: none;
        }

        a:hover {
            text-decoration: underline;
        }

        /* 左侧导航栏样式 */
        #sidebar {
            width: 200px;
            background-color: #333;
            color: white;
            padding: 15px;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
        }

        #sidebar a {
            color: white;
            padding: 10px;
            margin: 5px 0;
            text-decoration: none;
            display: block;
            border-radius: 4px;
            transition: background 0.3s;
        }

        #sidebar a:hover {
            background-color: #575757;
        }

        /* 右侧内容区样式 */
        #content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        /* 基本样式 */
        #avatarContainer {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            overflow: hidden;
            margin: 20px auto;
            border: 4px solid #008cba;
        }

        #avatarImg {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        form {
            max-width: 400px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }

        input[type="file"] {
            display: block;
            margin: 10px 0;
        }

        input[type="submit"] {
            display: block;
            width: 100%;
            padding: 10px;
            background-color: #008cba;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }

        input[type="submit"]:hover {
            background-color: #005f7f;
        }

        ul {
            max-width: 600px;
            margin: 20px auto;
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            list-style-type: none;
        }

        ul li {
            margin-bottom: 10px;
        }

        #logout {
            display: block;
            text-align: center;
            margin: 20px auto;
            background-color: #f44336;
            color: #fff;
            padding: 10px;
            width: 100px;
            border-radius: 4px;
            text-decoration: none;
        }

        #logout:hover {
            background-color: #c62828;
        }

        #avatarPreview img {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            border: 4px solid #008cba;
        }

        #login_box {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            text-align: center; /* 如果需要内容内文本居中 */
            margin: 0 auto; /* 自动左右居中 */
            width: 300px; /* 根据需要调整宽度 */
            border: 1px solid #ccc; /* 可选：添加边框样式 */
            padding: 20px; /* 可选：添加内边距 */
        }



    </style>
</head>
<body>
    <div id="sidebar">
        <h2>用户菜单</h2>
        <a href="#" onclick="showSection('profile')">个人资料</a>
        <a href="edit_article.html" onclick="">发布博客</a>
        <a href="#" onclick="showSection('articles')">我发布的文章</a>
        <a href="#" onclick="showSection('favorites')">我收藏的文章</a>
        <div id="adminLink"></div>
        <a href="login_form.html" id="logout">退出</a>
    </div>
    
    <div id="content">
        <div id="profile" class="section">
            <h2 style="text-align: center;">个人资料</h2>
            <div id="avatarContainer">
                <img id="avatarImg" src="" alt="用户头像">
            </div>
            <form id="uploadForm" enctype="multipart/form-data">
                <input type="file" name="avatar" id="avatarInput" accept="image/*">
                <input type="submit" value="上传新头像">
            </form>
            <div id="login_box">
                <h2>修改个人资料</h2>
                    <div id="input_box">
                        <input type="text" id="new_username" name="new_username" placeholder="请输入用户名">
                    </div>
                    <div id="input_box">
                        <input type="password" id="new_password" name="new_password" placeholder="请输入密码">
                    </div>
                    <div id="input_box">
                      <input type="phone" id="new_phone" name="new_phone" placeholder="请输入电话号码">
                  </div>
                    <button onclick="update_user()">确认修改</button>
            </div>
        </div>

        <div id="articles" class="section" style="display:none;">
            <h3>我发布的文章</h3>
            <ul id="articleList"></ul>
        </div>

        <div id="favorites" class="section" style="display:none;">
            <h3>我收藏的文章</h3>
            <ul id="favoriteList"></ul>
        </div>
    </div>

    <script>

        // 从 Cookie 中获取 JWT
        function getCookie(name) {
            let matches = document.cookie.match(new RegExp(
                "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
            ));
            return matches ? decodeURIComponent(matches[1]) : undefined;
        }

        const token = getCookie('token');
        // 设置带有 JWT 的 fetch 函数
        function fetchWithToken(url, options = {}) {
            options.headers = options.headers || {};
            options.headers['Authorization'] = 'Bearer ' + token;
            return fetch(url, options);
        }
        //获取用户信息
        fetchWithToken('profile.php')
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                    window.location.href = 'index.php';
                } else {
                    //检查是否为管理员并更新相应的UI
                    if (data.role === 'admin') {
                        document.getElementById('adminLink').innerHTML = '<a href="admin_review.php">审核文章</a>';
                    }
                }
            })
            .catch(error => console.error('获取用户信息失败：', error));
        
        // 获取当前用户头像和个人资料
        fetchWithToken('get_user_profile.php')
            .then(response => response.json())
            .then(data => {
                // 显示当前头像
                document.getElementById('avatarImg').src = data.avatarPath;
                document.getElementById('role');
            })
            .catch(error => console.error('获取用户信息失败：', error));

    
        // 提交修改头像的表单
        document.getElementById('uploadForm').addEventListener('submit', function(event) {
            event.preventDefault();

            var formData = new FormData();
            var file = document.getElementById('avatarInput').files[0];
            formData.append('avatar', file);

            fetchWithToken('upload_avatar.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    alert(data.error);
                } else {
                    // 显示上传的头像预览
                    document.getElementById('avatarPreview').innerHTML = "<img src='" + data.avatarPath + "' alt='上传的头像'>";
                    // 更新当前头像
                    document.getElementById('avatarImg').src = data.avatarPath;
                }
            })
            .catch(error => console.error('上传头像失败：', error));
        });

        // 获取当前用户发布的文章列表
        fetchWithToken('get_user_articles.php')
            .then(response => response.json())
            .then(data => {
                const articleList = document.getElementById('articleList');
                if (data.articles.length === 0) {
                    // 如果文章列表为空，显示暂无
                    const listItem = document.createElement('li');
                    listItem.textContent = '暂无发布';
                    articleList.appendChild(listItem);
                } else {
                    // 如果有文章，显示文章列表内容
                    data.articles.forEach(article => {
                        const listItem = document.createElement('li');
                        listItem.innerHTML = `<a href="article_detail.html?id=${article.id}">${article.title}</a> by ${article.author} on ${article.created_at}`;
                        articleList.appendChild(listItem);
                    });
                }
            })
            .catch(error => console.error('获取文章列表失败：', error));
        
        // 获取当前用户收藏的文章列表
        fetchWithToken('get_user_favorites.php')
            .then(response => response.json())
            .then(data => {
                const favoriteList = document.getElementById('favoriteList');
                if (data.favorites.length === 0) {
                    // 如果收藏列表为空，显示暂无
                    const listItem = document.createElement('li');
                    listItem.textContent = '暂无收藏';
                    favoriteList.appendChild(listItem);
                } else {
                    // 如果有收藏，显示收藏内容
                    data.favorites.forEach(favorite => {
                        const listItem = document.createElement('li');
                        listItem.innerHTML = `<a href="article_detail.html?id=${favorite.id}">${favorite.title}</a> by ${favorite.author} on ${favorite.created_at}`;
                        favoriteList.appendChild(listItem);
                    });
                }
            })
            .catch(error => console.error('获取收藏列表失败：', error));
        
        // 删除指定名称的 cookie
        function deleteCookie(name) {
            document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        }

        //退出功能
        document.getElementById('logout').addEventListener('click', function(event) {
            event.preventDefault();
            // 删除 JWT token cookie
            deleteCookie('token');
            // 重定向到登录页面
            window.location.href = 'login_form.html';
        });

        //修改个人信息功能
        function update_user() {
            var username = document.getElementById('new_username').value;
            var password = document.getElementById('new_password').value;
            var new_phone = document.getElementById('new_phone').value;

            var hashedPassword = '';

            // 使用 SHA-256 哈希密码
            if(password){
            hashedPassword = CryptoJS.SHA256(password).toString();
            }

            // 创建一个新的表单
            var form = document.createElement('form');
            form.method = 'POST';
            form.action = 'update_user.php';

            var usernameInput = document.createElement('input');
            usernameInput.type = 'hidden';
            usernameInput.name = 'new_username';
            usernameInput.value = username;

            var passwordInput = document.createElement('input');
            passwordInput.type = 'hidden';
            passwordInput.name = 'hashed_password';
            passwordInput.value = hashedPassword;

            var phoneInput = document.createElement('input');
            phoneInput.type = 'hidden';
            phoneInput.name = 'new_phone';
            phoneInput.value = new_phone;

            form.appendChild(usernameInput);
            form.appendChild(passwordInput);
            form.appendChild(phoneInput);
            document.body.appendChild(form);
            form.submit(); // 提交新表单
        }

        function showSection(sectionId) {
            const sections = document.querySelectorAll('.section');
            sections.forEach(section => {
                section.style.display = section.id === sectionId ? 'block' : 'none';
            });
        }
    </script>
</body>
</html>

